#include <stdio.h>
#include <windows.h>

#include <math.h>


// 电机参数
const float P = 5; // 极对数
const float lambda_m = 0.0016; // 永磁体磁链
const float Ld = 0.000035; // d轴电感
const float Lq = 0.00005; // q轴电感
const float Imax = 110.0; // 最大电流






// 计算MTPA电流参考值
void CalculateMTPACurrents(float Te, float *id_ref, float *iq_ref) {
    // 计算MTPA优化电流参考值
    float a = Lq / (2 * Ld);
    float b = -Te / (1.5 * P * lambda_m);
    float c = -Imax * Imax / (2 * Ld);
    
    // 求解二次方程 a*x^2 + b*x + c = 0
    float discriminant = b * b - 4 * a * c;
    if (discriminant >= 0) {
        float id1 = (-b + sqrt(discriminant)) / (2 * a);
        float id2 = (-b - sqrt(discriminant)) / (2 * a);
        
        // 选择合适的id
        *id_ref = (fabs(id1) < fabs(id2)) ? id1 : id2;
        *iq_ref = Te / (1.5 * P * (lambda_m + (Ld - Lq) * *id_ref));
    } else {
        // 无解，设置为最大电流下的安全值
        *id_ref = -Imax;
        *iq_ref = 0;
    }
}



int main()
{
       // 目标转矩
      float torque_ref = 1.0;

    // 使用MTPA策略计算d轴和q轴电流参考值

     float id_ref, iq_ref;
    CalculateMTPACurrents(torque_ref, &id_ref, &iq_ref);





    // 输出参考值
    printf("id_ref: %f, iq_ref: %f\n", id_ref, iq_ref);






    system("pause");
    return 0;
}